import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useTimerStore = defineStore('timer', () => {
  // 定义倒计时的状态
  const timeRemaining = ref(0); // 初始时间为60秒

  // 定义倒计时的定时器
  let timerId: any = null;

  // 开始倒计时的 action
  const startTimer = (num: number) => {
    timeRemaining.value = num;
    timerId = setInterval(() => {
      if (timeRemaining.value > 0) {
        timeRemaining.value--;
      } else {
        stopTimer();
      }
    }, 1000);
  };

  // 停止倒计时的 action
  const stopTimer = () => {
    if (timerId) {
      clearInterval(timerId);
      timerId = null;
    }
  };

  // 重置倒计时的 action
  const resetTimer = () => {
    stopTimer();
    timeRemaining.value = 60;
  };

  return { timeRemaining, startTimer, stopTimer, resetTimer, timerId };
}, {
  persist: {
    storage: sessionStorage,
  }
})